<?php
date_default_timezone_set('America/New_York');
function GetOrders(){
	$conn = GetConnection();
	return $conn->query('SELECT * FROM Orders');
}

function GetOrders_Sorted(){
	$conn = GetConnection();
	return $conn->query('SELECT * FROM Orders ORDER BY id DESC');
}

function GetOrder($id){
	$conn = GetConnection();
	if($id == null)
		die("No Order could be found. I.D. invalid.");
	$results = $conn->query("SELECT * FROM Orders WHERE id='$id'");
	$row = $results->fetch_assoc();
	$conn->close();
	return $row;
}

function EditOrder($row){
	$conn = GetConnection();
	$customer = $row['customer_id'];
	$amount = $row['amount'];
	$shipping_name = $row['shipping_name'];
	$address = $row['address'];
	$city = $row['city'];
	$zip = $row['zip'];
	$state = $row['state'];
	$country = $row['country'];
	$phone = $row['phone'];
	$tax = $row['tax'];
	$email = $row['email'];
	$tracking_number = $row['tracking_number'];
	$shipped = $row['shipped'];
	$date = $row['date'];
	$id = $row['id'];
	if(strlen($email) > 0)
	{
		$conn->query("UPDATE Orders SET Customers_id='$customer', amount='$amount',shipping_name='$shipping_name',
		address ='$address', city = '$city', state = '$state', zip = '$zip',country='$country',phone='$phone',tax='$tax',
		email='$email',date='$date',shipped='$shipped',tracking_number='$tracking_number' WHERE id = '$id'") or die(mysql_error());
	}
	else
		header("Location: http://cs.newpaltz.edu/~N02432643/%20web-course-2012/final/Orders/edit.php?id=".$id."");
	
	$conn->close();
}
function NewOrder($row){
	$customer = $row['customer_id'];
	$amount = $row['amount'];
	$shipping_name = $row['shipping_name'];
	$address = $row['address'];
	$city = $row['city'];
	$zip = $row['zip'];
	$state = $row['state'];
	$country = $row['country'];
	$phone = $row['phone'];
	$tax = $row['tax'];
	$email = $row['email'];
	$tracking_number = rand_string(80);
	$shipped = 0;
	

		$conn = GetConnection();
		$date = date("Y-m-d H:i:s");
		$conn->query("INSERT INTO Orders(id, Customers_id, amount, shipping_name, address, city, state, zip, country, phone, 
		tax, email, date, shipped, tracking_number) VALUES ('','$customer','$amount','$shipping_name','$address','$city','$state',
		'$zip','$country','$phone','$tax','$email','$date','$shipped','$tracking_number')") or die(mysql_error());
			$conn->close();
}

function DeleteOrder($id){
		$conn = GetConnection();
		$results = $conn->query("Delete FROM Orders WHERE id=$id");
		header('Location: http://cs.newpaltz.edu/~N02432643/%20web-course-2012/final/Orders/');
}

function rand_string( $length ) {
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";	
	$size = strlen( $chars );
	$str = '';
	for( $i = 0; $i < $length; $i++ ) {
		$str .= $chars[ rand( 0, $size - 1 ) ];
	}

	return $str;
}

function GetCustomers(){
	$conn = GetConnection();
	return $conn->query('SELECT * FROM Customers');
}